<template>
  <el-dialog v-model="state.visible" width="40%" title="编辑模板" :close-on-click-modal="false" draggable>
    <el-form ref="ruleFormRef" :model="state.dataForm" :rules="state.ruleValidate" label-width="80px">
      <el-card>
        <el-form-item label="关联栏目：" prop="columnId">
          <el-cascader v-model="state.dataForm.columnId" :options="state.columnOptions" :show-all-levels="false" style="width: 100%" />
        </el-form-item>
        <el-form-item label="模板标题：" prop="templateName">
          <el-input v-model="state.dataForm.templateName" placeholder="请输入模板标题名称" clearable></el-input>
        </el-form-item>
        <p class="header-title">
          <span>常规字段</span>
        </p>
        <el-checkbox v-for="(item, idx) in state.dataForm.field" :key="item.fieldName" v-model="state.dataForm.field[idx].required" size="default" class="cb">{{ item.name }}</el-checkbox>
      </el-card>
      <br />
      <el-card>
        <p class="header-title">
          <span>自定义字段</span>
        </p>
        <br />
        <div style="margin-bottom: 10px">
          <el-button type="primary" @click="handleAddRow">添加字段</el-button>
        </div>
        <el-table stripe :data="state.addRowData" style="width: 100%" row-key="id">
          <el-table-column type="index" label="序号" width="65"></el-table-column>
          <el-table-column prop="name" label="字段名">
            <template #default="scope">
              <el-input v-model="scope.row.name" size="small" placeholder="" @change="handleChange('name', scope.row.name, index)" />
            </template>
          </el-table-column>
          <el-table-column prop="type" label="字段类型">
            <template #default="scope">
              <div class="select-box">
                <el-select v-model="scope.row.type" transfer size="small" @ochange="handleChange('type', scope.row.type, index)">
                  <el-option v-for="item in state.typeList" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
                </el-select>
                &nbsp;
                <el-select v-model="scope.row.dictType" v-show="scope.row.type == 3" transfer size="small" @change="handleChange('dictType', scope.row.dictType, index)">
                  <el-option v-for="item in state.typeDictionaryList" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="required" label="是否必填">
            <template #default="scope">
              <el-switch v-model="scope.row.required" @change="handleChange('required', scope.row.required, index)" />
            </template>
          </el-table-column>
          <el-table-column prop="match" label="精准匹配">
            <template #default="scope">
              <el-switch v-model="scope.row.match" @change="handleChange('match', scope.row.match, index)" />
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作">
            <template #default="scope">
              <el-button type="danger" size="small" @click="handleDelRow(scope.row, index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <br />
    </el-form>
    <div class="footer">
      <el-button type="text" @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="state.showLoading" @click="handleSubmit">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { getTemplateListApi, submitTemplateApi, delColumnApi, getModelDictApi } from '@/api/cms/template'
import { getColumnTreeApi } from '@/api/cms/column'
const emit = defineEmits(['refreshDataList'])
import { renameObjectProperties } from '@/utils/common.js'

const fieldList = [
  {
    fieldName: 'title',
    name: '标题',
    type: '1',
    required: false,
    match: true,
    dictType: '',
  },
  {
    fieldName: 'author',
    name: '作者',
    type: '1',
    dictType: '',
    match: false,
    required: false,
  },
  {
    fieldName: 'firstPicture',
    name: '封面图',
    type: '7',
    dictType: '',
    match: false,
    required: false,
  },
  {
    fieldName: 'content',
    name: '正文',
    type: '2',
    dictType: '',
    required: false,
    match: true,
  },
  {
    fieldName: 'source',
    name: '原始来源',
    type: '1',
    dictType: '',
    match: false,
    required: false,
  },
  {
    fieldName: 'sourceUrl',
    name: '来源URL',
    type: '1',
    dictType: '',
    match: false,
    required: false,
  },
  {
    fieldName: 'keyword',
    name: '关键词',
    type: '1',
    dictType: '',
    match: false,
    required: false,
  },
  {
    fieldName: 'files',
    name: '附件',
    type: '8',
    dictType: '',
    match: false,
    required: false,
  },
]
const state = reactive({
  uploadFile: '/link/upload',
  visible: false,
  showLoading: false,
  roleList: [],
  dataForm: {
    id: 0,
    templateName: '',
    columnId: '',
    field: JSON.parse(JSON.stringify(fieldList)),
  },
  ruleValidate: {
    name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  },
  addRowVal: 1, // 增加行
  addRowColumns: [
    {
      title: '标号',
      slot: 'code',
      width: 80,
    },
    {
      title: '字段名',
      width: 120,
      slot: 'name',
    },
    {
      title: '字段类型',
      slot: 'type',
    },
    {
      title: '是否必填',
      slot: 'required',
      width: 100,
      align: 'center',
    },
    {
      title: '精确匹配',
      slot: 'match',
      width: 100,
      align: 'center',
    },
    {
      title: '操作',
      slot: 'action',
      width: 80,
    },
  ],
  typeList: [
    {
      value: '1',
      label: '输入框',
    },
    {
      value: '2',
      label: '文本域',
    },
    {
      value: '3',
      label: '下拉框',
    },
    {
      value: '4',
      label: '时间框',
    },
    {
      value: '5',
      label: '单选',
    },
    {
      value: '6',
      label: '多选',
    },
    {
      value: '7',
      label: '图片上传',
    },
  ],
  typeDictionaryList: [], //type类型的字典值
  addRowData: [], //自定义字段
  columnOptions: [], //栏目树形数据
})
const init = (row: any) => {
  getTypeDictionaryList()
  getColumnList()
  state.visible = true
  resetDataField(row)
  initAddRowData(row)
}
// 获取栏目树
const getColumnList = () => {
  getColumnTreeApi().then((res: any) => {
    if (res) {
      let arr = renameObjectProperties(res.data, 'columnName', 'label')
      arr = renameObjectProperties(arr, 'id', 'value')
      state.columnOptions = renameObjectProperties(arr, 'childColumnDetails', 'children')
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
// 获取字典值
const getTypeDictionaryList = () => {
  getModelDictApi({ ipi: 1, ips: 100, keyName: '' }).then((res: any) => {
    if (res && res.status === 200) {
      let arr = []
      res.data.result.map((v, index) => {
        arr.push({
          value: v.keyId,
          label: v.keyName,
        })
      })
      state.typeDictionaryList = arr
    } else {
      ElMessage.error(res.data.message)
    }
  })
}
// 初始化dataField
const resetDataField = (row) => {
  state.dataForm = {
    id: (row && row.id) || 0,
    templateName: (row && row.templateName) || '',
    columnId: row && row.columnId,
    field: JSON.parse(JSON.stringify(fieldList)),
  }
  if (!row) {
    return
  }
  //初始化默认属性
  let defaultProperty = (row && row.defaultProperty) || ''
  state.dataForm.field.forEach((item) => {
    let i = defaultProperty.findIndex((it) => {
      return it.fieldName == item.fieldName
    })
    if (i !== -1) {
      item.required = true
    }
  })
  state.addRowData = row?.property
}
// 初始化自定义字段
const initAddRowData = (row) => {
  if (row?.property) {
    let property = JSON.parse(JSON.stringify(row?.property))
    state.addRowData = property
  }
}
// 添加行
const handleAddRow = () => {
    state.addRowData.push({
      dictType: '',
      fieldName: `field${state.addRowVal}`,
      name: '',
      type: '1',
      required: false,
    })
  state.addRowVal ++ ;
}
// 删除行
const handleDelRow = (row, index) => {
  state.addRowData.splice(index, 1)
}
// 监听on-change事件
const handleChange = (type, value, index) => {
  // state.addRowData[index].type = value
}
const handleCancel = () => {
  state.visible = false
  state.showLoading = false
  state.addRowData = []
}
const ruleFormRef = ref(null)
const handleSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    // 表单提交
    if (valid) {
      state.showLoading = true
      let addRowData = JSON.parse(JSON.stringify(state.addRowData))
      let defaultProperty: any = []
      state.dataForm.field.map((item: any) => {
        if (item.required === true) {
          defaultProperty.push(item)
        }
      })
      let params = {
        templateName: state.dataForm.templateName.trim(),
        columnId: state.dataForm.columnId[0],
        property: addRowData, //自定义属性
        defaultProperty: defaultProperty, // 默认属性
      }
      if (state.dataForm.id) {
        params['id'] = state.dataForm.id
      }
      // 提交逻辑
      submitTemplateApi(params).then((res: any) => {
        if (res && res.status === 200) {
          ElMessage.success('操作成功')
          emit('refreshDataList')
          handleCancel()
          state.showLoading = false
        } else {
          ElMessage.warning('系统异常，稍后尝试')
          state.showLoading = false
        }
      })
    }
  })
}
defineExpose({
  init,
})
</script>

<style lang="scss" scoped>
.header-title {
  span {
    position: relative;
    display: inline-block;
    line-height: 20px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: normal;
    color: #2d8cf0;
    &:before {
      position: absolute;
      top: 50%;
      left: 0;
      width: 3px;
      height: 14px;
      margin-top: -8px;
      content: '';
      background-color: #2d8cf0;
    }
  }
}
.ivu-el-card {
  margin-bottom: 10px;
  .cb {
    width: 78px;
    margin-bottom: 10px;
  }
}
.inp1 {
  width: 150px;
}
.inp2 {
  width: 100px;
}
.inp3 {
  width: 70px;
  margin-right: 15px;
}
.list1 {
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #e8eaec;
}
.ivu-form-item {
  margin-bottom: 20px !important;
}
.formItem2 {
  color: red;
  .ivu-form-item-label {
    width: 110px !important;
  }
  .ivu-form-item-content {
    margin-left: 110px !important;
  }
}
.item-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 10px;
  .lab {
    margin-left: 10px;
    margin-right: 5px;
    font-size: 12px;
    transform: scale(0.98);
  }
}

.select-box {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  // flex-wrap: wrap;
  .ivu-select {
    max-width: calc(50% - 5px);
    margin-right: 10px;
    &:last-of-type {
      margin-right: 0;
    }
  }
}
.center-box {
  display: flex;
  align-items: center;
  justify-content: center;
}
.footer {
  display: flex;
  justify-content: flex-end;
}
</style>
